package com.toy.core.security.login.entrypoint;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.toy.core.config.SysConfig;
import com.toy.core.util.UrlUtils;

@Component("ntlmEntryPoint")
public class NtlmEntryPoint implements LoginEntryPoint {
	
	@Autowired
	private SysConfig sysConfig;

	public void commence(HttpServletRequest request,
			HttpServletResponse response,boolean containTarget) throws IOException, ServletException {
		StringBuffer redirectUrl = new StringBuffer();
		redirectUrl.append(request.getContextPath());
		redirectUrl.append(sysConfig.getNtmlLoginValidateUrl());
		if ( containTarget ){
			if (StringUtils.contains(redirectUrl.toString(), "?")) {
				redirectUrl.append("&");
			} else {
				redirectUrl.append("?");
			}
			redirectUrl.append("target=").append(
					URLEncoder.encode(UrlUtils.getRequestUrl(request), "UTF-8"));
		}
		response.sendRedirect(redirectUrl.toString());
	}
}
